package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.sql.Time;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public ShopServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id){
        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询缓存，有则返回，没有则查询数据库
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)){
            //存在
            //redis中取出来的数据转成Javabean
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //不存在，根据id查询数据库
        Shop shop = getById(id);
        //判断数据库是否查到
        if (shop == null){
            return Result.fail("店铺不存在");
        }
        //存在则写入Redis，并返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),0, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop){
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        //修改数据库中的数据
        updateById(shop);
        //删除Redis中的缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    //互斥锁解决缓存穿透，
    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY + id;
        //1.从redis查询缓存，有则返回，没有则查询数据库
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)){
            //存在
            //redis中取出来的数据转成Javabean
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //实现缓存重构
        String lockKey = "lock:shop"+id;
        Shop shop = null;
        try{
            boolean isLock = tryLock(lockKey);
            //判断是否获取成功
            if (!isLock){
                //获取失败,休眠50ms后在尝试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取成功,根据id查询数据库
            shop = getById(id);
            if (shop == null){
                //不存在，将空值写入Redis
                stringRedisTemplate.opsForValue().set(lockKey,"",CACHE_NULL_TTL);
                return null;
            }
            stringRedisTemplate.opsForValue().set(lockKey,JSONUtil.toJsonStr(shop),CACHE_NULL_TTL,TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //释放锁
            unlocl(lockKey);
        }
        return shop;
    }

    private void unlocl(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }

    private boolean tryLock(String lockKey) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    //缓存预热,设置的是逻辑过期
    public void saveShopRedis(Long id,Long expireSeconds){
        //查询店铺数据
        Shop shop = getById(id);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        //当前时间加上预计过期时长
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    //利用逻辑过期解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY +id;
        //从Redis查询商品缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)){
            return null;
        }
        //命中，将json反序列化，为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期则进行展示
            return shop;
        }
        //过期，则重建缓存
        //缓存重建，获取互斥锁，开启一个线程去进行重建，其余线程暂时返回旧数据
        String lockKey = LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            //获取成功
            CACHE_REBUILD_EXECUTOR.submit( () -> {
                try {
                    //rebuid cache
                    this.saveShopRedis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unlocl(lockKey);
                }
            });
        }
        //返回过期商家信息
        return shop;
    }

}
